# 处理音频速度

import os  
import re  
import ffmpeg  
import shutil  # 引入 shutil 用于复制文件

# 文件配置
updated_ch_file = r'D:\Documents\work\video\gitee\4\updated_ch.txt'  # 要读取的文本文件
output_folder = r'D:\Documents\work\video\gitee\4\output_wav_files'  # 存放音频文件的文件夹
processed_folder = 'processed_wav_files'  # 存放处理后的音频文件的文件夹
unprocessed_folder = 'unprocessed_wav_files'  # 存放未处理的音频文件的文件夹

# 创建输出文件夹
os.makedirs(processed_folder, exist_ok=True)  # 如果处理后的文件夹不存在，则创建它
os.makedirs(unprocessed_folder, exist_ok=True)

# 提取第1,3,4数值的函数
def extract_values(line):
    match = re.search(r'(\d+): \[(\d+), (\d+), .*?, (\d+)\]', line)
    if match:
        first_value = int(match.group(1))
        third_value = int(match.group(3))
        fourth_value = int(match.group(4))
        return first_value, third_value, fourth_value
    return None, None, None  

# 处理音频文件的函数
def process_audio(index, third_value, fourth_value):
    # 构造对应的音频文件名
    audio_file = os.path.join(output_folder, f"line_{index}.wav")
    
    if os.path.exists(audio_file):
        if fourth_value > third_value:
            # 使用 FFmpeg 进行音频变速处理
            output_file = os.path.join(processed_folder, f"line_{index}.wav")
            speed_factor = fourth_value / third_value
            try:
                # 调用 FFmpeg 进行音频处理
                ffmpeg.input(audio_file).filter('atempo', speed_factor).output(output_file).run(overwrite_output=True)
                print(f"Processed: {audio_file} to {output_file} with speed factor {speed_factor:.2f}")
            except ffmpeg.Error as e:
                print(f"Error processing {audio_file}: {e}")
        else:
            # 直接复制未处理的音频到 unprocessed 文件夹
            output_file = os.path.join(unprocessed_folder, f"line_{index}.wav")
            shutil.copy(audio_file, output_file)  # 使用 shutil.copy
            print(f"Unprocessed: {audio_file} copied to {unprocessed_folder}")
    else:
        print(f"File not found: {audio_file}")

if __name__ == "__main__":
    with open(updated_ch_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 遍历每一行，使用 enumerate 获取索引和行内容
    for index, line in enumerate(lines, start=1):
        first_value, third_value, fourth_value = extract_values(line)
        if third_value is not None and fourth_value is not None:
            print(f"第{first_value}行，第二个数值: {third_value}, 第四个数值: {fourth_value}")
            process_audio(index, third_value, fourth_value)
